import { processExpressionApi } from "@/api/bpm/task/processExpression";
import { BasicDrawer, useDrawerInner } from "@/components/Drawer";
import { BasicForm, FormSchema, useForm } from "@/components/Form";
import { message } from "antd";
import { useState } from "react";
import { useTranslation } from "react-i18next";
let reload: Function;
let id: string;
const timeFn = (time: string) => {
	if (!time) {
		return "";
	}
	const [date] = time.split(" ");
	return date;
};
const index = (props: { register: Fn }) => {
	const { t } = useTranslation();
	const en_vi = "task.processExpression";
	const formSchema: FormSchema[] = [
		{
			label: t(`${en_vi}.name`),
			field: "name",
			component: "Input"
		},
		{
			label: t(`${en_vi}.status`),
			field: "status",
			component: "Select",
			componentProps: {
				options: [
					{ label: t(`${en_vi}.open`), value: 0 },
					{ label: t(`${en_vi}.closed`), value: 1 }
				]
			}
		},
		{
			label: t(`${en_vi}.expression`),
			field: "expression",
			component: "Input"
		}
	];
	const [isAdd, setIsAdd] = useState(true);
	const [registerDrawer, { closeDrawer }] = useDrawerInner(props.register, data => {
		reload = data.reload;
		resetFields();
		if (data.record) {
			console.log(data.record);

			id = data.record.id;
			setFieldsValue(data.record);
			setIsAdd(false);
		}
	});

	const [register, { validateFields, setFieldsValue, resetFields }] = useForm({
		schemas: formSchema,
		labelWidth: 100,
		baseColProps: {
			span: 24
		}
	});
	const handleSubmit = async () => {
		const formValue = await validateFields();
		let api = processExpressionApi.processExpressionCreate;
		if (!isAdd) {
			api = processExpressionApi.processExpressionUpdate;
		}
		formValue.dateApproval = timeFn(formValue.dateApproval);
		formValue.dateFrom = timeFn(formValue.dateFrom);
		formValue.dateTo = timeFn(formValue.dateTo);
		const res = await api({ ...formValue, id });
		if (res) {
			id ? message.success(t("kevin_ui.addedSuccessfully")) : message.success(t("kevin_ui.updateSuccess"));
			reload();
			closeDrawer();
		}
	};
	return (
		<BasicDrawer showFooter={true} {...props} register={registerDrawer} ok={handleSubmit}>
			<BasicForm register={register}></BasicForm>
		</BasicDrawer>
	);
};
export default index;
